package com.fatcat.easybuy.controller;

import com.fatcat.easybuy.pojo.EasyBuyUser;
import com.fatcat.easybuy.service.EasyBuyUserService;
import com.fatcat.easybuy.service.EmailService;
import com.fatcat.easybuy.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author 郝秦毅
 * @since 2025/9/11 10:55
 */
@RestController
@RequestMapping("/email")
public class EmailController {

    @Autowired
    private EasyBuyUserService easyBuyUserService;
    @Autowired
    private EmailService emailService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/getCaptcha")
    public ResponseResult getCaptcha(@RequestParam("email") String email) {
        //判断邮箱是否为空
        if (email == null || email.equals("")) {
            return ResponseResult.error("邮箱不能为空");
        }
        //校验邮箱格式
        if (!email.matches("^[a-zA-Z0-9_.]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$")) {
            return ResponseResult.error("邮箱格式错误");
        }
        //判断邮箱是否存在
        EasyBuyUser easyBuyUser = easyBuyUserService.getUserByEmail(email);
        if (easyBuyUser != null && easyBuyUser.getEmail().equals(email)) {
            return ResponseResult.error("邮箱已存在");
        }

        //判断是否发送过验证码
        String emailAgainTime = email + "againTime";
        Object o = redisTemplate.opsForValue().get(emailAgainTime);
        if (o != null) {
            return ResponseResult.error("请稍后再发送");
        }

        //发送验证码
        String content = null;
        String subject = "邮箱验证码";
        String code = String.valueOf((int) (Math.random() * 900000 + 100000));
        //放入redis
        redisTemplate.opsForValue().set(email, code, 3, TimeUnit.MINUTES);
        redisTemplate.opsForValue().set(emailAgainTime, code, 1, TimeUnit.MINUTES);
        //发送邮件
        content = "【易买网】验证码 " + code + " 用于邮箱验证，3分钟内有效，请勿泄露和转发。如非本人操作，请忽略此短信。\n";
        emailService.sendSimpleEmail(email, "邮箱验证码", content);
        return ResponseResult.success().add("captchaCode", code);
    }

}
